import preferences from '@ohos.data.preferences'
import { CJLogUtil } from './CJLogUtil';

const TAG = "CJPreferencesUtils"

class CJPreferencesUtils {
  private static instance: CJPreferencesUtils;
  // 获取context后调用getRdbStore
  private data_pre: preferences.Preferences = null

  private constructor() {
  }

  public static getSingleton(): CJPreferencesUtils {
    if (!CJPreferencesUtils.instance) {
      CJPreferencesUtils.instance = new CJPreferencesUtils();
    }
    return CJPreferencesUtils.instance;
  }

  async init(config: {
    context: any,
    name?: string,
  }): Promise<void> {
    CJLogUtil.MODULE = 0x0001
    return new Promise<void>((resolve, reject) => {
      preferences
        .getPreferences(config.context, config.name || "cj_pre")
        .then(val => {
          CJLogUtil.info(TAG, "Get preferences successfully.")
          this.data_pre = val
          resolve()
        })
        .catch((err) => {
          CJLogUtil.error(TAG, "Get preferences failed, err: " + JSON.stringify(err))
          reject(err)
        })
    })
  }

  /**
   * 获取
   * @param key
   * @param value number | string | boolean | Array<number> | Array<string> | Array<boolean>;
   * @returns
   */
  get<T>(key, value: T): Promise<T> {
    // @ts-ignore
    return this.data_pre.get(key, value)
  }

  /**
   * 获取 json
   * @param key
   * @param value
   * @returns
   */
  getJson(key, value: any): Promise<any> {
    return new Promise<any>((resolve, reject) => {
      this.data_pre.get(key, "")
        .then(result => {
          try {
            // @ts-ignore
            if (result == null || result.trim() == '') {
              resolve(value)
            } else {
              resolve(JSON.parse(result as string))
            }
          } catch (err) {
            reject(err)
          }
        })
        .catch(reson => {
          reject(reson)
        })
    })
  }

  /**
   * 存储
   * @param key
   * @param value
   * @returns
   */
  put(key: string, value: preferences.ValueType): Promise<void> {
    return new Promise<void>((reslve, reject) => {
      this.data_pre.put(key, value)
        .then(() => {
          this.data_pre.flush()
          reslve()
        })
        .catch(reson => {
          CJLogUtil.info(TAG, reson)
          reject(reject)
        })
    })
  }
}

const uilt: CJPreferencesUtils = CJPreferencesUtils.getSingleton()

export { uilt as CJPreferencesUtils }